# -*- coding: utf-8 -*-
# @Time    : 2019/12/11 18:38
# @Author  : Damn7Kx
# @Software: PyCharm
import datetime
import json
import random
from urllib.parse import urlencode
import scrapy
from NewsSpider.items import NewsItem
from NewsSpider.tools.utils import Utils
from NewsSpider.tools.filter_time import Times
from NewsSpider.tools.parse_html import extract_html
from NewsSpider.tools.redis_db import Redis_DB
from w3lib.html import remove_tags


class AiKanNews(scrapy.Spider):
    '''
        api获取 详情页访问 时间戳翻页
    '''

    name = 'Aikan'
    # 奇趣 养生 军事 娱乐 社会 情感 搞笑 历史 生活
    types = ['p8f7zudy','xljkjlg2','yjsvt2od','dzb71c07','ako5pdl7',
             'a27odvv1','desy4cow','1uirkt2r','9tv31d9b']

    Ua = [
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/72.0.3626.101 Mobile/15E148 Safari/605.1",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/15.0b13894 Mobile/16D57 Safari/605.1.15",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/8.1.1 Mobile/16D57 Safari/605.1.15",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/16.0.14.122053 Mobile/16D57 Safari/9537.53",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPT/2 Mobile/16D57",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) OPiOS/12.0.5.3 Version/7.0 Mobile/16D57 Safari/9537.53",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 EdgiOS/42.10.3 Mobile/16D57 Safari/605.1.15",
        "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16D57 unknown BingWeb/6.9.8.1",
    ]
    headers = {
        "User-Agent": random.choice(Ua),
    }
    t = Times()
    count = 0
    redis = Redis_DB()

    custom_settings = {
        'DOWNLOADER_MIDDLEWARES': {
            'NewsSpider.middlewares.FakeUserAgentMiddleware': 543,
            'NewsSpider.middlewares.ProxyIPMiddleware': 544,
            'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
        },
        'ITEM_PIPELINES': {
            'NewsSpider.pipelines.KafkaPipeline': 544,
        }
    }
    def start_requests(self):
        for type in self.types:
            querystring = {"aid": "3aeuwplk", "size": "9",
                           "slip": "timeline", "cid": type, "since": "0"}
            params = urlencode(querystring)
            base_url = 'https://www.aiotecho.com/v7/res/list?'
            url = base_url + params
            # print(url)
            yield scrapy.Request(url, headers=self.headers,callback=self.parse_text,dont_filter=True,meta={"type":type})

    def parse_text(self,response):
        if self.__class__.count > 150:
            # 在引擎关闭该爬虫
            self.crawler.engine.close_spider(self, '计数超过150，停止爬虫!')
        print("正在访问详情页:",response.url)
        # 没次翻页增加计数
        self.__class__.count += 1
        datas = json.loads(response.text)
        data_ = datas['data']
        createTime = str(data_[-1]['createTime'])
        type = response.meta['type']
        # 下一页的翻页
        url = f"https://www.aiotecho.com/v7/res/list?aid=3aeuwplk&size=9&slip=timeline&cid={type}&since={createTime}"
        yield scrapy.Request(url, headers=self.headers, callback=self.parse_text, dont_filter=True,meta={"type":type})
        for d in data_:
            dicts = {}
            url = d['shareLink']
            dataSource = d['origin']
            id = Utils.url_hash(url)
            title = d['title']
            pubdate_datetime = d['publishTime']
            pubdate = Utils.process_timestamp(pubdate_datetime)
            pubdate = str(self.t.datetimes(pubdate))
            dicts['url'] = url
            dicts['id'] = id
            dicts['title'] = title
            dicts['pubdate'] = pubdate
            dicts['dataSource'] = dataSource
            if not self.t.time_is_Recent(pubdate):
                yield None
            if self.redis.check_exist_2("wenzhangquchong", id, '') == 0:
                print('该id:%s已存在' % id)
                yield None
            else:
                # 获取详情页
                yield scrapy.Request(url=url,headers=self.headers,callback=self.parse,dont_filter=True,meta=dicts)

    def parse(self, response):
        # print(response.text)
        item = NewsItem()
        try:
            content = remove_tags(response.css("#content div:nth-child(1) div").extract_first())
        except:
            content = extract_html(response.text)
        item['id'] = response.meta['id']
        item['url'] = response.meta['url']
        item['title'] =response.meta['title']
        item['pubdate'] =response.meta['pubdate']
        item['content'] =content
        item['author'] = response.meta['dataSource']
        item['formats'] = "web"
        item['dataSource'] = response.meta['dataSource']
        item['serchEnType'] = "爱看新闻"
        item['html'] = content
        item['updateTime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        item['collectProcess'] = 'crawl_news'
        item['serverIp'] = "113.128.12.74"
        yield item